package com.yinxing.webapi.config;

import com.yinxing.framework.shiro.filter.ShiroJsonOutPutFilter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import java.util.Arrays;

@Configuration
public class FilterConfig {

    /**
     * 计算reponse当中的Content-Length
     * springmvc @ResponseBody注解 把对象序列化为json
     * 默认情况会按 Transfer-Encoding: chunked 返回 缺少Content-Length响应头
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterBean = new FilterRegistrationBean();
        filterBean.setFilter(new ShallowEtagHeaderFilter());
        filterBean.setUrlPatterns(Arrays.asList("*"));
        filterBean.setOrder(1);
        return filterBean;
    }

    /**
     * Shiro权限异常拦截处理
     * 输出位JSON格式数据
     */
    @Bean
    public FilterRegistrationBean jsonShiroFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new ShiroJsonOutPutFilter());
        registration.setName("shiroJsonOutPutFilter");
        registration.setOrder(2);
        registration.addUrlPatterns("/*");
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.INCLUDE, DispatcherType.ERROR);
        return registration;
    }

    /**
     * Shiro全局权限拦截器
     */
    @Bean
    public FilterRegistrationBean springShiroFilter(ShiroFilterFactoryBean shiroFilterFactoryBean) throws Exception {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter((Filter) shiroFilterFactoryBean.getObject());
        registration.setName("springShiroFilter");
        registration.setOrder(3);
        registration.addUrlPatterns("/*");
        registration.addInitParameter("targetFilterLifecycle", "true");
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.INCLUDE, DispatcherType.ERROR);
        return registration;
    }

}
